<?php


namespace Plugin\ProductCategory;


use Beike\Models\Category;
use Plugin\ProductCategory\Resources\CategoryResource;

class Bootstrap
{
    public function boot()
    {
        /**
         * 增加分类搜索
         */
        add_hook_blade("admin.categories.create.after", function ($callback, $output, $data) {
            $view = view('ProductCategory::admin.categories_search', $data)->render();
            return $output . $view;
        }, 20250428143512);


        /**
         * 分类搜索结果
         */
        add_hook_filter('admin.category.index.data', function ($data) {
            if (request()->keyword && trim(request()->keyword) != '') {
                $keyword = request()->keyword;

                $builder        = Category::query()->with('description')->whereHas('description', function ($query) use ($keyword) {
                    $query->where('name', 'like', "%{$keyword}%");
                });
                $findCategories = $builder->get([
                    'id',
                    'parent_id'
                ]);
                $parentIDs      = [];
                foreach ($findCategories as $findCategory) {
                    $this->getParentIDs($parentIDs, $findCategory);
                }

                $categories = Category::with([
                    'description',
                    'children.description',
                    'children.children.description'
                ])->whereIn('id', $parentIDs)->where('parent_id', 0)->get();

                request()->merge(['ids' => $parentIDs]);
                $data['categories'] = CategoryResource::collection($categories);

            }


            return $data;
        }, 20250428143512);

        add_hook_blade("admin.product.edit.category", function ($callback, $output, $data) {

            //$source['categories']


            $categories = Category::with([
                'description',
                'children.description',
                'children.children.description'
            ])->where('parent_id', 0)->where('active', true)->get();


            $data['source']['categories2'] = \Beike\Admin\Http\Resources\CategoryResource::collection($categories);

            $view = view('ProductCategory::admin.category', $data)->render();
            return $view;
        }, 20250428143512);


        add_hook_blade("header.menu.before", function ($callback, $output, $data) {

            $setting = plugin_setting("product_category");
            if (!isset($setting['open_menu']) || empty($setting['open_menu'])) {
                return $output;
            }

            $categories = Category::query()->with(['description'])->where('active', true)->orderBy("position")->orderBy("id")->orderBy("updated_at")->get();
            foreach ($categories as $category) {
                $category->go_url = $category->getUrlAttribute();
            }
            //CategoryResource::collection($categories);
            $categories = $categories->toArray();
            $categories = $this->generateTree($categories, 0);
            // print_r(json_encode($categories));exit;
            $view = view('ProductCategory::shop.categories_menu', ['categories_menus' => $categories])->render();
            return $view . $output;
        }, 20250428143512);
        add_hook_blade("header.menu.mobile.before", function ($callback, $output, $data) {

            $setting = plugin_setting("product_category");
            if (!isset($setting['open_menu']) || empty($setting['open_menu'])) {
                return $output;
            }

            $categories = Category::query()->with(['description'])->where('active', true)->orderBy("position")->orderBy("id")->orderBy("updated_at")->get();
            foreach ($categories as $category) {
                $category->go_url = $category->getUrlAttribute();
            }
            //CategoryResource::collection($categories);
            $categories = $categories->toArray();
            $categories = $this->generateTree($categories, 0);
            // print_r(json_encode($categories));exit;
            $view = view('ProductCategory::shop.categories_menu_mobile', ['categories_menus' => $categories])->render();
            return $view . $output;
        }, 20250428143512);


        add_hook_blade('admin.product.batch_btns.before', function ($callback, $output, $data) {
            $categories = Category::with([
                'description',
                'children.description',
                'children.children.description'
            ])->where('parent_id', 0)->where('active', true)->get();


            $categories = \Beike\Admin\Http\Resources\CategoryResource::collection($categories);

            $view       = view('ProductCategory::admin.batch_set_category', ['categories_tree' => $categories])->render();
            return $view . $output;
        }, 20250428143512);
    }


    private function getParentIDs(&$parentIDs, $findCategory)
    {
        $parentIDs[] = $findCategory->id;
        if ($findCategory->parent_id != 0) {
            $findCategory = Category::query()->where("id", $findCategory->parent_id)->first([
                'id',
                'parent_id'
            ]);
            $this->getParentIDs($parentIDs, $findCategory);
        }
    }

    private function generateTree($items, $parentId = 0)
    {
        $tree = [];
        foreach ($items as $item) {
            if ($item['parent_id'] == $parentId) {
                $children = $this->generateTree($items, $item['id']);
                if ($children) {
                    $item['children'] = $children;
                }
                $tree[] = $item;
            }
        }
        return $tree;
    }

}
